package com.ruanyun.modular.downWord;


import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alibaba.druid.support.json.JSONUtils;
import com.google.gson.JsonObject;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import com.spire.doc.*;
import org.tio.utils.json.Json;

public class ToWord extends BaseController {
    public static void toWord (Map<String, Object> dataMap, String docName, Template t, HttpServletResponse resp) throws IOException, TemplateException {
        String fileName = URLEncoder.encode(docName,"UTF-8") + UUID.randomUUID().toString()+ ".docx";


        try {
            Document doc = new Document();

            resp.setContentType("application/msword;charset=UTF-8");
            //2.设置文件头：最后一个参数是设置下载文件名
            resp.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            Writer out1 = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream(), "utf-8"),10240);
            t.process(dataMap, out1);
            out1.close();
//            OutputStreamWriter write = null;
//            OutputStream servletOS = resp.getOutputStream();
//             String  test = servletOS.toString();
//            ByteArrayInputStream bs = new ByteArrayInputStream(test.getBytes());
////            ByteArrayOutputStream bs = (ByteArrayOutputStream) servletOS;
//            write = new OutputStreamWriter(servletOS);
//            t.process(dataMap, write);
//
////            ByteArrayInputStream buffer = new ByteArrayInputStream(bs.toByteArray());
//            doc.loadFromStream(bs, FileFormat.Word_Xml);
//
//
//            ByteArrayOutputStream byteos = new ByteArrayOutputStream();
//            doc.saveToFile(byteos,FileFormat.Docx);

//            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
